import requests
import csv
import os


def open_list_csv():
    if os.path.exists("../../static/csv/month.csv"):  # 如果文件存在
        # 删除文件，可使用以下两种方法。
        os.remove('../../static/csv/month.csv')  # 则删除
    with open('../../static/csv/month.csv', 'w', newline='', encoding='utf-8') as file:
        csv.writer(file).writerow(['date', 'confirm', 'dead', 'heal','suspect'])


def write_list_csv(x1, x2, x3, x4, x5):
    with open('../../static/csv/month.csv', 'a', newline='', encoding='utf-8') as file:
        csv.writer(file).writerow([x1, x2, x3, x4, x5])


def get_china_day_list():
    url = 'https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=chinaDayList,chinaDayAddList,' \
          'nowConfirmStatis,provinceCompare '
    data_list = requests.get(url).json()['data']['chinaDayAddList']

    open_list_csv()

    for t in data_list:
        # 日期
        date = t['date']
        # 累计确诊
        confirm = t['confirm']
        # 死亡人数
        dead = t['dead']
        # 治愈人数
        heal = t['heal']
        # 疑似病人
        suspect = t['suspect']
        write_list_csv(date, confirm, dead, heal, suspect)


get_china_day_list()
